package org.egedede.processmanager.ui;

import java.util.List;

import javax.swing.AbstractListModel;

import org.egedede.processmanager.ProcessDefinition;
import org.egedede.processmanager.ProcessManager;
import org.egedede.processmanager.SingleProcess;
import org.egedede.processmanager.events.ProcessEvent;
import org.egedede.processmanager.events.ProcessListener;

public class ProcessManagerListModel extends AbstractListModel implements ProcessListener {

   private final ProcessManager manager;

   public ProcessManagerListModel(ProcessManager manager) {
      this.manager = manager;
      this.manager.addListener(this);
   }

   @Override
   public int getSize() {
      return this.manager.list().size();
   }

   @Override
   public Object getElementAt(int index) {
      return this.manager.list().get(index);
   }

   @Override
   public void processChanged(ProcessEvent e) {
      List<ProcessDefinition> list = this.manager.list();
      switch (e.getType()) {
      case ProcessEvent.STARTED:
         int size = list.size();
         this.fireIntervalAdded(this, size, size);
         break;
      case ProcessEvent.FINISHED:
         int index = -1;
         int i = 0;
         SingleProcess process = e.getProcess();
         for (ProcessDefinition def : list) {
            if (process.equals(def.getProcess())) {
               index = i;
               break;
            }
         }
         if (index != -1) {
            this.fireIntervalAdded(this, index, index);
         }
         break;

      default:
         break;
      }

   }
}
